﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

using SManaApi.Services;

using SManaModel;
using SManaModel.dtos;
using SManaModel.entities;
using SManaModel.reqs;
using SManaModel.utils;

namespace SManaApi.Controllers;

/// <summary>
/// 审批模块
/// </summary>
public class ApproveController : MasterController<ApproveController>
{
    private readonly IWebHostEnvironment _hostingEnvironment;
    protected readonly StudentService _studentService;
    protected readonly ApproveService _approveService;
    protected readonly ProcessService _processService;
    protected readonly JwtService _jwtService;

    public ApproveController(ILogger<ApproveController> logger,
        MyDbContext dbContext,
        ApproveService approveService,
        JwtService jwtService,
        IWebHostEnvironment hostingEnvironment, StudentService studentService, ProcessService processService) : base(logger,
        dbContext)
    {
        _approveService = approveService;
        _jwtService = jwtService;
        _hostingEnvironment = hostingEnvironment;
        _studentService = studentService;
        _processService = processService;
    }

    /// <summary>
    /// 学生获取审批信息
    /// </summary>
    /// <param name="pageDto">分页条件</param>
    /// <returns></returns>
    [HttpGet("student")]
    public ApiResult GetApprovesForStudent([FromQuery] SearchPageDto pageDto)
    {
        var stuId = _jwtService.GetId(HttpContext);
        var pageApiResult = _approveService.GetApprovesForStudent(pageDto, stuId);
        return ApiResult.Page(pageApiResult);
    }

    /// <summary>
    /// 教师获取审批信息
    /// </summary>
    /// <param name="pageDto">分页条件</param>
    /// <returns></returns>
    [HttpGet("teacher")]
    public ApiResult GetApprovesForTeacher([FromQuery] SearchPageDto pageDto)
    {
        var teaId = _jwtService.GetId(HttpContext);
        var list = _approveService.GetApprovesForTeacher(pageDto, teaId);
        return ApiResult.Page(list!);
    }

    /// <summary>
    /// 获取发展进程
    /// </summary>
    /// <returns></returns>
    [HttpGet("process")]
    public async Task<ApiResult> Process()
    {
        var stuId = _jwtService.GetId(HttpContext);
        if (stuId > 0)
        {
            var entities = _processService.GetEntities();
            var processEntities = await entities?.Where(t => t.StudentId == stuId).ToListAsync();
            return ApiResult.Ok(data: processEntities);
        }
        return ApiResult.FailOfParams();
    }

    /// <summary>
    /// 查看是否时扩展类型
    /// </summary>
    class ExtensionComparer : IEqualityComparer<string>
    {
        public bool Equals(string? x, string? y)
        {
            return x.Equals(y, StringComparison.CurrentCultureIgnoreCase);
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }


    /// <summary>
    /// 批准和反驳
    /// </summary>
    /// <param name="id">审批id</param>
    /// <param name="order">培养人序号</param>
    /// <param name="ok">true 批准, false 反驳</param>
    /// <returns></returns>
    [HttpGet("apply")]
    public ApiResult Apply([FromQuery] int id, [FromQuery] int order, [FromQuery] bool ok)
    {
        var teaId = _jwtService.GetId(HttpContext);
        if (teaId > 0)
        {
            var n = _approveService.ApplyApprove(id, teaId, ok, order);
            return ApiResult.Judge(n);
        }
        return ApiResult.FailOfParams();
    }

    /// <summary>
    /// 分配培养人
    /// </summary>
    /// <param name="req">参数</param>
    /// <returns></returns>
    [HttpPost("assign")]
    public ApiResult Assignment([FromBody] AssignmentReq req)
    {
        if (req.StuId < 1)
        {
            return ApiResult.FailOfParams();
        }

        var n = _approveService.JudgeApplyTeacher(req.StuId, req.TeaId);
        if (n > 0)
        {
            return ApiResult.Fail("此老师已经被选为此学生的培养人, 请选择其他老师");
        }
        n = _studentService.AssignmentTeacher(req.StuId, req.TeaId, req.Order);
        return ApiResult.Judge(n);
    }

    /// <summary>
    /// 取消申请
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("cancel")]
    public ApiResult Cancel([FromQuery] string? id)
    {
        if (id is null)
        {
            return ApiResult.FailOfParams();
        }

        var n = 0;
        id.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .ToList()
            .ForEach(idStr =>
            {
                if (int.TryParse(idStr, out var i))
                {
                    n += _approveService.CancelApproveForStudent(i);
                }
            });
        return ApiResult.Judge(n);
    }

    /// <summary>
    /// 上传资料
    /// </summary>
    [HttpPost("upload")]
    public ApiResult Upload([FromForm] int? id)
    {
        if (id == null || id.Value < 1)
        {
            return ApiResult.FailOfParams();
        }

        var formFileCollection = Request.Form.Files;
        var formFile = formFileCollection.FirstOrDefault();
        var allowExtensions = new List<String>
        {
            ".doc",
            ".docx"
        };
        if (formFile != null)
        {
            var fileName = formFile.FileName;
            var extension = Path.GetExtension(fileName);
            if (allowExtensions.Contains(extension, new ExtensionComparer()))
            {
                var filePath = $"wwwroot/UploadFile/{fileName}";
                var fileFullPath = _hostingEnvironment.ContentRootPath + filePath;

                var approveEntity = _approveService.GetEntity(t => t.Id == id)?.FirstOrDefault();
                if (approveEntity != null)
                {
                    approveEntity.DocPath = $"static/{fileName}";
                    var n = _approveService.UpdateEntity(approveEntity);
                    if (n > 0)
                    {
                        using var fs = System.IO.File.Create(fileFullPath);
                        formFile.CopyTo(fs);
                        fs.Flush();
                    } // 如果数据库保存成功就写入服务器

                    return ApiResult.Judge(n);
                }
                else
                {
                    return ApiResult.Fail("申请不存在");
                }
            }
            else
            {
                return ApiResult.Fail("不允许的扩展类型");
            }
        }
        return ApiResult.FailOfParams();
    }

    /// <summary>
    /// 添加党员申请信息
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    [HttpPost]
    public ApiResult Add([FromBody] ApproveReq req)
    {
        var stuId = _jwtService.GetId(HttpContext);
        var entity = req.ConvertTo<ApproveEntity>();
        entity.ApplyStudentId = stuId;
        entity.CDate = DateTime.Now;
        var n = _approveService.AddEntity(entity);
        n = n > 0 ? entity.Id : n;
        return ApiResult.Judge(n);
    }

    /// <summary>
    /// 删除申请信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    public ApiResult Delete([FromQuery] string? id)
    {
        if (id is null)
        {
            return ApiResult.FailOfParams();
        }

        var n = 0;
        id.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .ToList()
            .ForEach(idStr =>
            {
                if (int.TryParse(idStr, out var i))
                {
                    n += _approveService.DeleteEntity(entity => entity.Id == i);
                }
            });
        return ApiResult.Judge(n);
    }

    /// <summary>
    /// 修改申请信息
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    [HttpPut]
    public ApiResult Update([FromBody] ApproveUpdateReq req)
    {
        var r = general_update(req, _approveService);
        return r;
    }

}